package com.dabao.controller.admin;

import com.dabao.controller.BaseController;
import com.dabao.util.CacheUtils;
import com.dabao.util.CookieUtils;
import org.apache.commons.lang.StringUtils;
import com.dabao.bean.User;
import com.dabao.service.UserService;
import com.dabao.util.MD5Utils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by dabao on 16/3/4.
 */
@Controller
@RequestMapping("/admin/login")
public class LoginController extends BaseController {

    private final static String ERROR_USERNAME ="用户不存在";

    private final static String ERROR_PASSWORD ="密码错误";

    @Resource
    private UserService userService;

    @RequestMapping(value = "", method = {RequestMethod.GET})
    public String login() {
        return "admin/login";
    }

    /**
     * 用户登录写入cookie跳转到index页面
     * @param response
     * @param username
     * @param password
     * @param saveLogin
     * @param model
     * @return
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String login(HttpServletResponse response,
                        @RequestParam("username") String username,
                        @RequestParam("password") String password,
                        @RequestParam(value = "saveLogin", required = false) Integer saveLogin, Model model) {
        User user = userService.findByUsername(username);
        if(user == null) {
            model.addAttribute("error", ERROR_USERNAME);
        }

        else if(!StringUtils.equals(user.getPassword(), MD5Utils.md5(password))) {
            model.addAttribute("error", ERROR_PASSWORD);
        }

        else {
            CacheUtils.put(username, user);
            CookieUtils.login(response, user, saveLogin !=null && saveLogin == 1);
            return redirect("/admin/index");
        }
        return "admin/login";
    }




}
